function ChunkedText_(splitSize){
    this._chunks = [];
    this._splitSize = splitSize || 8192;
}
ChunkedText_.prototype = {
    getText: function (){
        return this._chunks.join('');
    },
    setText: function (text){
        this._chunks = [];
        this.replaceText(0, 0, text);
    },
    getSubstring: function (offset, length){
        var chunks = this._chunks;
        var indexes = this.getIndexes_(offset, length);
        var index = indexes[0];
        var endIndex = indexes[2];
        return index == endIndex ?
            (chunks[index] ? chunks[index].slice(indexes[1], indexes[3]) : '') : [
                chunks[indexes[0]] ? chunks[indexes[0]].slice(indexes[1]) : '',
                chunks.slice(indexes[0] + 1, indexes[2]).join(''),
                chunks[indexes[2]] ? chunks[indexes[2]].slice(0, indexes[3]) : ''
            ].join('');
    },
    // NOTE: 在跨域chunk做indexOf的时候，需要前一个chunk的末尾一点点补到第二个chunk前面再indexOf.
    indexOf: function (text, startIndex){
        // todo:
    },
    getIndexes_: function (offset, length){
        var chunks = this._chunks;
        var index = 0;
        var chunk;
        while (chunk = chunks[index]) {
            if (offset > chunk.length) {
                offset -= chunk.length;
                index ++;
            } else {
                break;
            }
        }
        var endIndex = index;
        var endOffset = offset + length;
        while (chunk = chunks[index]) {
            if (endOffset > chunk.length) {
                endOffset -= chunk.length;
                endIndex ++;
            } else {
                break;
            }
        }
        return [index, offset, endIndex, endOffset];
    },
    replaceText: function (offset, length, text){
        var splitSize = this._splitSize;
        var tidySize = splitSize >> 1;
        var chunks = this._chunks;
        var chunk;
        var indexes = this.getIndexes_(offset, length);
        var index = indexes[0];
        offset = indexes[1];
        var endIndex = indexes[2];
        var endOffset = indexes[3];
        var restChunks = [chunks[index] ? chunks[index].slice(0, offset) : '',
            text, chunks[endIndex] ? chunks[endIndex].slice(endOffset) : ''];
        var lastChunk;
        if (chunks[index - 1]) {
            lastChunk = chunks[index - 1];
            index --;
        } else {
            lastChunk = '';
        }
        var tidyChunks = [];
        for (var i=0; i<restChunks.length; i++) {
            lastChunk += restChunks[i];
            while (lastChunk.length > splitSize) {
                tidyChunks.push(lastChunk.slice(0, tidySize));
                lastChunk = lastChunk.slice(tidySize);
            }
        }
        tidyChunks.push(lastChunk);
        var array = [index, endIndex + 1 - index];
        array.push.apply(array, tidyChunks);
        array.splice.apply(chunks, array);
    }
};
